package com.xiaolin.Thread.synchronization;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName ReentrantReadWriteLockTest
 * @Description ReentrantReadWriteLock 实现线程安全，允许多线程读，一个线程写
 * @Detail detail
 * @Author MyPC
 * @Date 2020/12/1
 * @Version 1.0
 */
public class ReentrantReadWriteLockTest {
    public static void main(String[] args) {
        for (int i=0;i<100;i++){
            new TwoThread().start();
        }
    }
}

class TwoThread extends Thread{
    // 所有线程共用一份读锁对象
    private static ReentrantReadWriteLock.ReadLock readLock=new ReentrantReadWriteLock().readLock();
    // 所有线程共用一份写锁对象
    private static ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock();
    @Override
    public void run() {
        readLock();
    }

    public static void readLock(){
        // 读锁锁住之后，线程还是可以进来
        readLock.lock();
        try {
            System.out.println(Thread.currentThread()+"线程锁住了");
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println(Thread.currentThread()+"线程释放了");
        }
    }
    public static void writeLock(){
        // 写锁锁住之后，只能有一个线程进来
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread()+"线程锁住了");
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
            System.out.println(Thread.currentThread()+"线程释放了");
        }
    }
}
